import { defineStore } from 'pinia'
import { songDetailType, songsUrlType } from './type'
import { ref } from 'vue'
import { getSongDetailApi, getSongUrlApi, getLyricApi } from '@renderer/api'
export const useSongDetailStore = defineStore('songDetailStore', () => {
  // 歌曲详情
  const songDetail = ref<songDetailType[]>([])
  // 获取歌曲列表url
  const songsUrl = ref<songsUrlType[]>([])
  // 单首歌曲详情
  const song = ref({} as songDetailType)
  // 歌曲id
  const songId = ref(0)
  // 歌词数组
  const lyricArr = ref<string[]>([])
  // 歌词时间数组
  const timeArr = ref<string[]>([])

  // 播放进度
  const currentTime = ref(0)
  // 获取歌曲详情
  const getSongDetail = async (id: number) => {
    songId.value = id
    const res = await getSongDetailApi(songId.value)
    songDetail.value = res.songs
    song.value = songDetail.value[0]
  }
  const getSongUrl = async (id: number) => {
    songId.value = id
    const res = await getSongUrlApi(songId.value)
    songsUrl.value = res.data
  }
  const getLyric = async () => {
    // 清空歌词数组和歌词时间数组
    lyricArr.value = []
    timeArr.value = []

    const res = await getLyricApi(songId.value)
    let arr = res.lrc.lyric.split('\n')
    // 使用正则表达式匹配时间戳和歌词
    arr.forEach((item) => {
      const match = item.match(/^\[(\d{2}:\d{2}\.\d{2,3})\](.*)$/)
      if (match) {
        timeArr.value.push(match[1])
        match[2] = match[2].replace('，', '')
        lyricArr.value.push(match[2])
      }
    })
  }

  return {
    song,
    songId,
    songDetail,
    songsUrl,
    lyricArr,
    timeArr,
    currentTime,
    getSongDetail,
    getSongUrl,
    getLyric
  }
})
